package main

import (
	"flag"
	"os"
	"strings"

	Log "github.com/tsif/component/log"
	"github.com/tsif/utils"
)

var ARG_TEMPFILES = flag.String("tempfiles", "", "模板文件列表, \",\"分隔符, 多个模板文件会按顺序合并起来生成")
var ARG_OUTPATH = flag.String("outpath", "", "文件输出路径")
var ARG_DBURL = flag.String("dburl", "root:admin@tcp(localhost:3306)/codebook?charset=utf8", "数据库url")
var ARG_DBTABLE_REGX = flag.String("dbtableregx", ".*", "数据库表正则筛选值")
var ARG_EXT_PARAMS = flag.String("extparams", "", "额外参数, \",\"分割, 用于传入模板中使用")

func main() {
	// 默认参数
	if len(os.Args) <= 1 {
		// os.Args = []string{os.Args[0],
		// 	"-tempfiles", "tf/Golang.tmpl,tf/Info.tmpl", "-outpath", "out\\entity",
		// 	"-dburl", "root:admin@tcp(localhost:3306)/codebook?charset=utf8",
		// 	"-extparams", "package=entity,b=1,c=, d"}
		// os.Args = []string{os.Args[0],
		// 	"-tempfiles", "tf/Golang.tmpl,tf/Dao.tmpl", "-outpath", "../codebook/component/dao/",
		// 	"-dburl", "root:admin@tcp(localhost:3306)/codebook?charset=utf8",
		// 	"-dbtableregx", "t_u_account",
		// 	"-extparams", "package=dao,package_entity=codebook/component/entity"}
		// os.Args = []string{os.Args[0],
		// 	"-tempfiles", "tf/Golang.tmpl,tf/ListDao.tmpl", "-outpath", "../codebook/component/dao/",
		// 	"-dburl", "root:admin@tcp(localhost:3306)/codebook?charset=utf8",
		// 	"-dbtableregx", "t_u_record",
		// 	"-extparams", "package=dao,package_entity=codebook/component/entity"}
		os.Args = []string{os.Args[0],
			"-tempfiles", "tf/Golang.tmpl,tf/ListDao.tmpl", "-outpath", "../codebook/component/dao/",
			"-dburl", "root:admin@tcp(localhost:3306)/codebook?charset=utf8",
			"-dbtableregx", "t_u_storage",
			"-extparams", "package=dao,package_entity=codebook/component/entity"}
	}

	// 运行参数
	Log.Info("process start args", os.Args, len(os.Args))

	// 解析参数
	flag.Parse() // 需先构建参数再解析
	tempFiles := *ARG_TEMPFILES
	outPath := *ARG_OUTPATH
	dburl := *ARG_DBURL
	dbTableRegx := *ARG_DBTABLE_REGX
	extParamsStr := *ARG_EXT_PARAMS

	// 模板文件解析
	fileList := strings.Split(tempFiles, ",")
	tempFileList := make([]string, 0, len(fileList))
	for _, f := range fileList {
		tempFileList = append(tempFileList, f)
	}

	// 额外参数解析
	extParams := utils.SplitMap(extParamsStr, ",", "=")
	Log.Info("params ", extParams)

	// db read
	tables, err_p := DBParse(dburl, dbTableRegx)
	if err_p != nil {
		Log.Error("db parse error! ", err_p.Error())
		return
	}
	// make order
	orders, err_o := MakeOrder(tables, "*")
	if err_o != nil {
		Log.Error("db make order error! ", err_o.Error())
		return
	}

	// 遍历order
	for _, order := range *orders {
		order.Params = *extParams

		// 生成文件
		err_f := MakeFile(&order, fileList, outPath)
		if err_f != nil {
			Log.Error("make file error! ", err_f.Error())
		}
		// break
	}

	// stop app
	os.Exit(0)
}
